import eCharts from "@/plugins/echarts";
import type { EChartCoreOption } from "@/plugins/echarts";

import { shallowRef, onMounted, onDeactivated, onBeforeUnmount } from "vue";
import type { Ref } from "vue";

export const useEChart = (elRef: Ref<HTMLElement>, options: EChartCoreOption) => {
  // 实例
  const charts = shallowRef<eCharts.ECharts>();

  // 初始化
  const init = () => {
    charts.value = eCharts.init(elRef.value);
    setOptions(options);
  };

  // 配置
  const setOptions = (options: EChartCoreOption) => {
    charts.value?.setOption(options);
  };

  // 注册地图
  const registerMap = (mapName: string, geoJson: any) => {
    eCharts.registerMap(mapName, geoJson);
  };

  // resize
  const resize = () => {
    charts.value?.resize();
  };

  // 监听页面 resize 节流防抖根据实际情况处理
  onMounted(() => {
    window.addEventListener("resize", resize);
  });

  // 防止 keepAlive 继续监听页面
  onDeactivated(() => {
    window.removeEventListener("resize", resize);
  });

  // 页面卸载之前移除监听
  onBeforeUnmount(() => {
    window.removeEventListener("resize", resize);
  });

  return {
    init,
    setOptions,
    resize,
    registerMap,
  };
};
